package com.ruicar.afs.cloud.afscase.approvetask.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.approvemakelabel.entity.ApproveMakeLabel;
import com.ruicar.afs.cloud.afscase.approvemakelabel.service.ApproveMakeLabelService;
import com.ruicar.afs.cloud.afscase.approvetask.condition.WorkTaskPoolCondition;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkProcessScheduleInfo;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkTaskPool;
import com.ruicar.afs.cloud.afscase.approvetask.service.CaseApproveRecordService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkProcessScheduleInfoService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolHistoryService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolService;
import com.ruicar.afs.cloud.afscase.approvetask.vo.ApproveTaskVo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCarInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseCarInfoService;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.LabelPositionEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ProcessTypeEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author jiaqi.guo
 * @version 1.0
 * @description:经我处理
 * @created 2020/7/11 16:11
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api("经我处理")
@RequestMapping("/approve")
public class DealWithTaskController {

    private WorkTaskPoolHistoryService workTaskPoolHistoryService;

    private CaseCarInfoService caseCarInfoService;

    private CaseBaseInfoService caseBaseInfoService;

    private ApproveMakeLabelService approveMakeLabelService;

    private CaseApproveRecordService caseApproveRecordService;

    private WorkProcessScheduleInfoService workProcessScheduleInfoService;

    private WorkTaskPoolService workTaskPoolService;


    @PostMapping(value = "/queryDealWithTaskList")
    @ApiOperation(value = "经我处理")
    public IResponse<IPage<ApproveTaskVo>> queryDealWithTaskList(@ModelAttribute WorkTaskPoolCondition condition) {
        //流程类型条件
        List processList = new ArrayList();
        processList.add(ProcessTypeEnum.FORMAL_REVIEW.getCode());
        processList.add(ProcessTypeEnum.GENERA_APPROVE.getCode());
        processList.add(ProcessTypeEnum.INVENTORIES_ARE.getCode());
        processList.add(ProcessTypeEnum.RECONSIDER_APPLY.getCode());
        processList.add(ProcessTypeEnum.SECONDARY_FRAUD.getCode());
        condition.setProcessTypeList(processList);

        //特殊流程类型条件
        List processTypeSpecial = new ArrayList();
        processTypeSpecial.add(ProcessTypeEnum.CHANGE_ASSETS.getCode());
        condition.setProcessTypeSpecial(processTypeSpecial);
        //获取标签Id
        String[] str = condition.getTag();
        List labelIdList = new ArrayList();
        if (str!=null&&str.length>0) {
            for (int i = 0; i < str.length; i++) {
                labelIdList.add(str[i]);
            }
        }
        if (labelIdList != null && labelIdList.size() > 0) {
            condition.setLabelList(labelIdList);
        }
        //当前登录用户
        String useName = SecurityUtils.getUsername();
        condition.setDisposeStaff(useName);
        IPage<ApproveTaskVo> pageResult = workTaskPoolHistoryService.queryDealWithTaskList(
                new Page(condition.getPageNumber(), condition.getPageSize()),
                condition);
        List<String> stageIdList = new ArrayList<>();
        for (ApproveTaskVo record : pageResult.getRecords()) {
            if(StringUtils.isNotEmpty(record.getStageId())){
                stageIdList.add(record.getStageId());
            }
        }
        Map<String,WorkTaskPool> currentStagePoolMap=new HashMap<>();
        if(CollectionUtil.isNotEmpty(stageIdList)){
            currentStagePoolMap.putAll(workTaskPoolService.list(
                    Wrappers.<WorkTaskPool>lambdaQuery()
                            .in(WorkTaskPool::getStageId,stageIdList)
            ).stream().collect(Collectors.toMap(WorkTaskPool::getStageId, Function.identity(),(exists,current)-> exists)));

        }


        pageResult.getRecords().forEach(approveTaskVo -> {
            /**案件基础信息*/
            CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                    .eq(CaseBaseInfo::getApplyNo, approveTaskVo.getApplyNo()));
            /**车辆信息*/
            CaseCarInfo caseCarInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda()
                    .eq(CaseCarInfo::getApplyNo, approveTaskVo.getApplyNo()));

            if (ObjectUtils.isNotEmpty(caseBaseInfo)) {
                // 当前时间，毫秒
                Long nowMilliSeconds = System.currentTimeMillis();
                // 开始时间，毫秒
                Long submitDateMilliSeconds = approveTaskVo.getStartTime().getTime();
                Long effectTimeReckon = caseBaseInfo.getEffectTimeReckon();
                int seconds = Convert.toInt((effectTimeReckon + nowMilliSeconds - submitDateMilliSeconds) / 1000, 0);
                String hour = StringUtils.leftPad(seconds / 3600 + "", 2, '0');
                String minute = StringUtils.leftPad((seconds % 3600) / 60 + "", 2, '0');
                String second = StringUtils.leftPad((seconds % 3600) % 60 + "", 2, '0');
                // 原始读秒
                approveTaskVo.setOriginalSeconds(seconds);
                // 计时时间，页面初始化时显示
                approveTaskVo.setTimming(hour + " : " + minute + " : " + second);
                // 拼接车辆信息显示
            }
            if (Objects.nonNull(caseCarInfo)) {
                approveTaskVo.setCarName(caseCarInfo.getModelName());
            }
            /**  标签信息 **/
            List<ApproveMakeLabel> labelList = approveMakeLabelService.list(Wrappers.<ApproveMakeLabel>query().lambda()
                    .eq(ApproveMakeLabel::getApplyNo, approveTaskVo.getApplyNo())
                    .eq(ApproveMakeLabel::getLabelLocation, LabelPositionEnum.LIST.getCode()));
            approveTaskVo.setLabelList(labelList);
            /**处理命令*/
            String remainDataInfo = approveTaskVo.getRemainData();
            if (StringUtils.isNotEmpty(remainDataInfo)) {
                JSONObject jsonObject = JSONObject.parseObject(remainDataInfo);
                String remainInfd = jsonObject.getString("record");
                JSONObject remin = JSONObject.parseObject(remainInfd);
                String remainDada = remin.getString("approveSuggestName");
                approveTaskVo.setRemainData(remainDada);
            }
            /** 流程信息 */
            WorkProcessScheduleInfo info = workProcessScheduleInfoService.getById(approveTaskVo.getStageId());
            if (Objects.nonNull(info)) {
                approveTaskVo.setFirstTrail(WhetherEnum.YES.getCode().equalsIgnoreCase(info.getFirstTrail()));
                approveTaskVo.setLastTrail(WhetherEnum.YES.getCode().equalsIgnoreCase(info.getLastTrail()));
            }

            WorkTaskPool currentPool = currentStagePoolMap.getOrDefault(approveTaskVo.getStageId(),new WorkTaskPool());
            approveTaskVo.setDisposeCode(currentPool.getApproveStaff());
            approveTaskVo.setDisposeStaff(currentPool.getApproveStaffName());

        });
        return IResponse.success(pageResult);

    }

}
